package team.knowers.qzhserver.common.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configurers.*;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;
import team.knowers.qzhserver.common.component.JwtAuthenticationTokenFilter;
import team.knowers.qzhserver.common.component.RestAuthenticationEntryPoint;
import team.knowers.qzhserver.common.component.RestfulAccessDeniedHandler;

/**
 * SpringSecurity的配置
 *
 * @author xtg
 * @date 2024/2/10 14:59
 */
@Configuration
@EnableWebSecurity
public class SecurityConfig {

    @Autowired
    private IgnoreUrlsConfig ignoreUrlsConfig;
    @Autowired
    private RestfulAccessDeniedHandler restfulAccessDeniedHandler;
    @Autowired
    private RestAuthenticationEntryPoint restAuthenticationEntryPoint;
    @Autowired
    private JwtAuthenticationTokenFilter jwtAuthenticationTokenFilter;

    @Bean
    SecurityFilterChain filterChain(HttpSecurity httpSecurity) throws Exception {
        return httpSecurity.authorizeHttpRequests(auth -> {
            ignoreUrlsConfig.getUrls().forEach(url -> auth.requestMatchers(new AntPathRequestMatcher(url)).permitAll());
                    auth.anyRequest().permitAll();//测试使用
//                    auth.anyRequest().authenticated();二者二取一
                })
                .addFilterBefore(jwtAuthenticationTokenFilter, UsernamePasswordAuthenticationFilter.class)
                .exceptionHandling(handler -> {
                    handler.accessDeniedHandler(restfulAccessDeniedHandler);
                    handler.authenticationEntryPoint(restAuthenticationEntryPoint);
                })
                .sessionManagement(auth -> auth.sessionCreationPolicy(SessionCreationPolicy.STATELESS))
                .csrf(AbstractHttpConfigurer::disable).build();
    }

}
